﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/*
 * TH07 Groep 10
 * ----------------------------------------------------------------------------------
 * Versie   Door        Commentaar
 * 0.1      Luca        Opzet en programmeer werk
 * 0.2      Erwin       Verplaatst naar Algorithms, 
 *                      aangepast om als reference te gebruiken
 */

namespace Algorithms.Tools
{
    class QuickSort
    {
        // array of integers to hold values
        private int[] a;

        // number of elements in array
        private int x;

        public int X
        {
            set { x = value; }
            get { return x; }
        }
        public int[] Array
        {
            get
            {
                return a;
            }
        }
        // Quick Sort Algorithm

        public QuickSort(int[] arr)
        {
            a = arr;
            x = arr.Length;
        }

        public void sortArray()
        {
            q_sort(0, x - 1);
        }

        public void q_sort(int left, int right)
        {
            int pivot, l_hold, r_hold;

            l_hold = left;
            r_hold = right;
            pivot = a[left];

            while (left < right)
            {
                while ((a[right] >= pivot) && (left < right))
                {
                    right--;
                }

                if (left != right)
                {
                    a[left] = a[right];
                    left++;
                }

                while ((a[left] <= pivot) && (left < right))
                {
                    left++;
                }

                if (left != right)
                {
                    a[right] = a[left];
                    right--;
                }
            }

            a[left] = pivot;
            pivot = left;
            left = l_hold;
            right = r_hold;

            if (left < pivot)
            {
                q_sort(left, pivot - 1);
            }

            if (right > pivot)
            {
                q_sort(pivot + 1, right);
            }
        }
    }
}
